import redis


class Lock:
    def __init__(self,client,key):
        self.client = client
        self.key = key

    # TODO 超时自动释放锁
    def acquire(self):
        # 尝试获取锁，成功时候返回True,失败时返回False
        # NX选项的值确保了代表锁的字符串键只会在没有值的情况下被设置
        result = self.client.set(self.key,VALUE_OF_LOCK,nx = True)
        return result is True

    # TODO 释放锁的时候，对身份没有验证
    def release(self):
        # 尝试释放锁，成功时候返回True,失败时返回False
        return self.client.delete(self.key)==1



VALUE_OF_LOCK="locking"

if __name__ == "__main__":
    # 使用文本编码的方式打开客户端
    r = redis.StrictRedis(host="127.0.0.1", port=6379, db=0, decode_responses=True)
    r_lock = Lock(r,"test_lock")
    if not r_lock.acquire():
        r_lock.release()
    print("是否成功获取锁: {}".format(r_lock.acquire()))